<?php

namespace App\Console\Commands;

use App\Enum\SmsScheduleEnum;
use App\Lib\sms\AliSms;
use App\Models\SmsScheduleModel;
use Illuminate\Console\Command;

class sendSmsScheduleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'sms:send-schedule {send_num?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '定时发送短信';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $realSend = env('SMS_REAL_SEND',true);
        $fakeResponse=json_decode('{"Message":"OK","RequestId":"fakeResponse","Code":"OK","BizId":"fakeResponse"}');
        while(1) {
            $sencond = date('s');

            if ($sencond >= 55) {
                $this->info("sencond = $sencond, wait for next time.");
                break;
            }else  $this->info("sencond = $sencond, keep going.");
            $sendNum = $this->argument('send_num') ?? 10;
            $rows = SmsScheduleModel::query()->where('status', '=', SmsScheduleEnum::SMS_STATUS_UNSEND)->orderBy('id', 'asc')->limit($sendNum)->get()->toArray();
            if (!empty($rows)) {
                foreach ($rows as $row) {
                    $params = empty($row['params']) ? '' : json_decode($row['params']);

                    if( $realSend !== false )$result = AliSms::send($row['mobile'], $params, $row['template_id']);
                    else $result = $fakeResponse;

                    $data = ['result' => json_encode($result)];
                    if ($result->Code == 'OK') {
                        $data['status'] = SmsScheduleEnum::SMS_STATUS_SENT;
                    } else {
                        $data['status'] = SmsScheduleEnum::SMS_STATUS_FAILED;
                    }
                    SmsScheduleModel::query()->where(['id' => $row['id']])->update($data);
                }
            }
            sleep(2);
        }
        //
        return 0;
    }
}
